package com.luban.authserver.config.customfilter.login;

import com.luban.authserver.config.customfilter.login.handler.CustomAuthenticationFailureHandler;
import com.luban.authserver.config.customfilter.login.handler.CustomAuthenticationSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义登录验证拦截器逻辑  这里并没有做用户名密码验证。 用户名密码验证是 CustomAuthenticationProvider
 * <p>
 * 仿造 默认登录过滤器 UsernamePasswordAuthenticationFilter 实现
 */
@Component
public class CustomAuthenticationProcessingFilter extends AbstractAuthenticationProcessingFilter {
    public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "username";
    public static final String SPRING_SECURITY_FORM_BIZYEAR_KEY = "bizyear";
    public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "password";

    private String usernameParameter = SPRING_SECURITY_FORM_USERNAME_KEY;
    private String passwordParameter = SPRING_SECURITY_FORM_PASSWORD_KEY;
    private boolean postOnly = true;

    /**
     * @param authenticationManager: 认证管理器
     * @param successHandler:        认证成功处理
     * @param failureHandler:        认证失败处理
     */
    public CustomAuthenticationProcessingFilter(CustomAuthenticationManager authenticationManager, CustomAuthenticationSuccessHandler successHandler, CustomAuthenticationFailureHandler failureHandler) {
        super(new AntPathRequestMatcher("/login", "POST"));
       // super(new AntPathRequestMatcher("/oauth/token", "POST"));
        this.setAuthenticationManager(authenticationManager);
        this.setAuthenticationFailureHandler(failureHandler);
        this.setAuthenticationSuccessHandler(successHandler);
    }


    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        if (postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }

        String username = obtainUsername(request);
        String password = obtainPassword(request);

        // 登录需要额外的参数，示例
        String year = obtainYear(request);
        if (year == null) {
            throw new RuntimeException("Parameter bizyear can not be null");
        }

        if (username == null) {
            username = "";
        }


        if (password == null) {
            password = "";
        }

        username = username.trim();

        // 构建认证信息 就是把用户名 和密码封装成一个对象
        CustomAuthenticationToken authRequest = new CustomAuthenticationToken(
                username, password);

        // Allow subclasses to set the "details" property
        // 填充用户信息
        setDetails(request, authRequest);

        return this.getAuthenticationManager().authenticate(authRequest);

    }

    protected String obtainUsername(HttpServletRequest request) {
        return request.getParameter(usernameParameter);
    }

    protected String obtainYear(HttpServletRequest request) {
        return request.getParameter(SPRING_SECURITY_FORM_BIZYEAR_KEY);
    }

    protected String obtainPassword(HttpServletRequest request) {
        return request.getParameter(passwordParameter);
    }

    protected void setDetails(HttpServletRequest request,
                              CustomAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }
}
